/*!
 * Copyright (c) 2011 David I. Lehn <dil@lehn.org>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

(function($) {
   $(document).ready(function() {
      // Snippet from http://diveintohtml5.org/forms.html
      if (!("autofocus" in document.createElement("input"))) {
         $(".autofocus").focus();
      }

      $('a.vote').click(function() {
         var poll = $(this).data('poll');
         var vote = $(this).data('tag');
         //console.log('voted', poll, vote);
         $.ajax({
            type: 'POST',
            url: window.location.href,
            data: {
               vote: vote
            },
            success: function() {
               var vel = $('.votes[data-poll=' + poll + '][data-tag=' + vote + ']');
               var votes = parseInt(vel.text());
               vel.text(votes + 1);
            }
         });
         return false;
      });

      $('span.votes').each(function(i, el) {
         var poll = $(el).data('poll');
         var vote = $(el).data('tag');
         //console.log('load votes', poll, vote);
         $.ajax({
            type: 'GET',
            url: window.location.href,
            data: {
               vote: vote
            },
            success: function(data) {
               //console.log(data);
               $(el).text(data.votes);
            },
            error: function() {
               $(el).text("-");
            }
         });
      });
   });
})(jQuery)
